# -*- coding: utf-8 -*-

"""
@Author  : James.xiaoli
@Time    : 2025/4/15 17:50
@File    : app.py
模块注释：主入口文件
    

"""
import time

from PyQt5.QtGui import QPixmap

import upload
from helper import generate_qr, clear_directory
from ui.main import *
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox
import sys
import pyperclip
import uuid
import os


class appWindow(QMainWindow):
    def __init__(self):
        super(appWindow, self).__init__()
        # 初始化窗体，设置样式
        self.file_path = None
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        # self.setWindowFlag(Qt.FramelessWindowHint)
        # self.setAttribute(Qt.WA_TranslucentBackground)
        self.ui.progressBar.setVisible(False)

        # 设置按钮按钮点击事件
        self.ui.pushButton_chose.clicked.connect(lambda: self.push_button_chose())
        self.ui.pushButton_upload.clicked.connect(lambda: self.push_button_upload())
        self.ui.pushButton_copy.clicked.connect(lambda: self.push_button_copy(True))
        self.ui.pushButton_create_qrcode.clicked.connect(lambda: self.push_button_create_qrcode())
        self.ui.pushButton_copy_qrcode.clicked.connect(lambda: self.push_button_copy_qrcode(True))
        self.ui.pushButton_copy_qrcode_2.clicked.connect(lambda: self.push_button_copy_qrcode(False))
        # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
        self.show()
        # self.showFullScreen()
        self.initialize()


    def initialize(self):
        clear_directory('./qrcode')


    def push_button_chose(self):
        file_path, _ = QFileDialog.getOpenFileName(self, "选择文件", "", "所有文件 (*.*)")
        if file_path:
            self.ui.textBrowser_input.setText(file_path)  # 显示文件路径
        self.file_path = file_path

    def push_button_upload(self):
        self.set_upload_processing()
        file = time.strftime("%Y%m%d", time.localtime())
        unique_id = uuid.uuid4()
        extension = os.path.splitext(self.file_path)[1]
        file = f"{file}/{unique_id}{extension}"
        self.up = upload.Upload(file, self.file_path)
        self.up.progress_signal.connect(self.progress_handler)
        self.up.finished.connect(self.set_upload_finish)
        self.up.start()



    def push_button_copy(self, show = False):
        """通用文本复制（优先使用pyperclip）"""
        out_text = self.ui.textEdit_out.toPlainText()
        try:
            pyperclip.copy(out_text)
        except:
            # 备用Qt方案
            app = QApplication([])
            clipboard = QApplication.clipboard()
            clipboard.setText(out_text)
        if  show:
            QMessageBox.information(self, "提示", "复制成功！")


    def push_button_copy_qrcode(self, is_logo = False):
        """通用文本复制（优先使用pyperclip）"""
        img = self.ui.label_qrcode.pixmap() if is_logo else self.ui.label_qrcode_2.pixmap()

        clipboard = QApplication.clipboard()
        clipboard.setPixmap(img)


        QMessageBox.information(self, "提示", "复制成功！")



    def progress_handler(self, progress):
        self.ui.progressBar.setValue(progress)


    def set_upload_processing(self):
        self.ui.progressBar.setVisible(True)
        self.ui.progressBar.setValue(0)
        self.set_status(False)



    def set_upload_finish(self,  data):
        self.ui.progressBar.setValue(100)
        err, ret = data
        if err == 0:
            self.ui.textEdit_out.setText(ret)
            self.push_button_copy()
            self.push_button_create_qrcode(False)
            QMessageBox.information(self, "提示", "文件上传完成！链接已复制到剪切板，粘贴即可。")
        else:
            QMessageBox.information(self, "提示", "上传失败！")
        self.set_status(True)



    def push_button_create_qrcode(self, show=True):
        ret = self.ui.textEdit_out.toPlainText()
        self.ui.label_qrcode.setPixmap(QPixmap(generate_qr(ret, True)))
        self.ui.label_qrcode_2.setPixmap(QPixmap(generate_qr(ret, False)))
        if show:
            QMessageBox.information(self, "提示", "生成二维码成功！")


    def set_status(self, status):
        self.ui.pushButton_upload.setEnabled(status)
        self.ui.pushButton_chose.setEnabled(status)
        self.ui.pushButton_copy.setEnabled(status)
        self.ui.pushButton_copy_qrcode.setEnabled(status)
        self.ui.pushButton_copy_qrcode_2.setEnabled(status)
        self.ui.pushButton_create_qrcode.setEnabled(status)
        self.ui.textEdit_out.setEnabled(status)



if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = appWindow()
    window.setWindowTitle("七牛云文件上传工具")
    window.show()
    sys.exit(app.exec())
